package com.kiki.oauth.service;

import com.kiki.oauth.bean.UserInfo;
import com.kiki.oauth.dao.AccountDao;
import com.kiki.oauth.dao.PermissionDao;
import com.kiki.oauth.dao.UserDao;
import com.kiki.oauth.entity.Account;
import com.kiki.oauth.entity.Permission;
import com.kiki.oauth.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private PermissionDao permissionDao;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountDao.selectByAccount(username);
        if(account==null){
            throw new UsernameNotFoundException("user "+username+" is not exists!");
        }
        User user = userDao.selectById(account.getUserId());
        if(user==null){
            throw new UsernameNotFoundException("user "+username+" is not exists!");
        }

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        //获取用户权限
        List<Permission> permissions = permissionDao.selectByUserid(user.getId());
        if(!CollectionUtils.isEmpty(permissions)) {
            //设置用户权限
            permissions.forEach(permission -> {
                authorities.add(new SimpleGrantedAuthority(permission.getCode()));
            });
        }

        //返回认证用户
        return new UserInfo(user.getId(), username, user.getPassword(), authorities);
    }

}
